//获取应用实例
import {showToastError} from "../../../utils/tool";
import {getAreaText} from "../../../service/postage";
import {str2arr} from "../../../utils/str";
import {getAllAreas} from "../../../service/location";

const app = getApp();

Component({
    options:{
        styleIsolation: 'apply-shared',
    },

    properties: {
        // data: {type: Array, value: []},//传递的列表信息
        // show: {type: Boolean, value: false},//是否显示
        value: {
            type: Array|String, value: '',
            observer(data){

               getAllAreas().then(areas => {
                   // 设置初始选中状态
                   let newList = areas
                   if (data){
                       newList = this.get_initial(areas, data)
                   }

                   // 设置选中地区文字
                   const text = getAreaText(areas, data)

                   this.setData({
                       list:newList,
                       _text:text,
                   })
               })

            }
        },
        placeholder: {type:String, value:"请选择"}
    },
    data: { // 私有数据，可用于模版渲染
        _show:false,
        _text:'',

        list: [],//处理好的列表信息
        html: '',//递归出树状结构代码
    },
    lifetimes:{
        created() {
            // this.setData({
            //     list:app.globalData.areas
            // })
            // console.log("组件北闯将",this.data)
        },
        attached() {
            (async () => {
                getAllAreas().then(areas => {
                    this.setData({
                        list:areas
                    })
                })

            })()
        }
    },
    methods: {

        open(){
            this.setData({
                _show:true,
            })
        },

        /**
         * 根据选项的选中状态的切换，处理下级选项的选中状态
         * @param {需要处理的下级选项列表信息} data
         * @param {需要修改为的选中状态(0：未选中 1：已选中 -1：部分选中)} checked_status
         */
        set_child_checked: function (data, checked_status) {
            var that = this;
            var list = [];
            data.forEach(item => {
                var self = item;
                self.child = self.child === undefined ? [] : self.child;

                //修改当前选项的选中状态
                self.checked_status = checked_status;

                //修改下级的选中状态
                if (self.child.length > 0) {
                    self.child = that.set_child_checked(self.child, checked_status);
                }

                list.push(self);
            })

            return list;
        },
        /**
         * 根据下级选项的选中状态，递归处理上级的选中状态
         * @param {需要处理的父级选项列表信息} data
         */
        set_parent_checked: function (data) {
            var that = this;
            var list = [];
            data.forEach(item => {
                var self = item;
                var child = self.child === undefined ? [] : self.child;

                var checked_status = self.checked_status;//当前选项的选中状态
                if (child.length > 0) {
                    //递归处理下级的选中状态
                    child = that.set_parent_checked(child);

                    //通过遍历下级选项的选中状态，判断当前选项的选中状态

                    var child_checked_status = [];//当前下级的选中状态集合
                    child.forEach(c => {
                        if (child_checked_status.indexOf(c.checked_status) == -1) {
                            child_checked_status.push(c.checked_status);
                        }
                    })
                    if (child_checked_status.length > 1) {//说明下级中存在未全部选中的信息
                        checked_status = -1;//当前选项的选中状态为部分选中
                    } else {//说明下级中信息的选中状态都是同一状态
                        //当前选项的选中状态为下级的统一状态
                        checked_status = child_checked_status.length > 0 ? child_checked_status[0] : 0;
                    }
                }

                self.checked_status = checked_status;
                self.child = child;
                list.push(self);
            })

            return list;
        },
        /**
         * 根据传递的value与data值，获取初始tree列表信息
         */
        get_initial: function (data, value) {
            var that = this;
            value = str2arr(value)

            // 转为数字
            value = value.map(item => parseInt(item))


            var list = [];
            data.forEach(item => {
                var self = item;
                var child = self.child === undefined ? [] : self.child;

                //若当前信息ID在value中存在，则当前信息为全选状态
                if (value.indexOf(self.id) > -1) {
                    self.checked_status = 1;
                    //当前选项的下级选项同样改为全选状态
                    self.child = that.set_child_checked(child, 1);
                } else {//当前选项不是全选状态，则递归到下级查看
                    if (child.length > 0) {
                        self.child = that.get_initial(child);
                    }
                    //递归处理上级的选中状态
                    self = that.set_parent_checked([self])[0];
                }

                list.push(self);
            })

            return list;
        },
        /**
         * 展开关闭状态切换
         */
        open_close: function (e) {
            var that = this;
            var self = this.get_self(e);
            var is_open = self.is_open;
            self.is_open = !is_open;
            var list = that.set_list(e, self);
            that.setData({list: list});
        },
        /**
         * 选中状态切换
         */
        checked_status: function (e) {
            var self = this.get_self(e);
            var checked_status = self.checked_status;
            checked_status = checked_status == 1 ? 0 : 1;//未全部选中则改为全部选中，反之全部取消

            //处理下级选项的选中状态
            self = this.set_child_checked([self], checked_status)[0];
            var list = this.set_list(e, self);
            //递归处理上级的选中状态
            list = this.set_parent_checked(list);
            this.setData({list: list});
        },
        /**
         * 获取当前信息内容
         */
        get_self: function (e) {
            var level = e.currentTarget.dataset.level;
            var p_i = e.currentTarget.dataset.p_i;
            var c_i = e.currentTarget.dataset.c_i;
            var d_i = e.currentTarget.dataset.d_i;
            var list = this.data.list;
            var self = {};//当前信息
            if (level == 'p') {//省
                self = list[p_i];
            } else if (level == 'c') {//市
                self = list[p_i].child[c_i];
            } else if (level == 'd') {//区
                self = list[p_i].child[c_i].child[d_i];
            }

            return self;
        },
        /**
         * 修改列表信息
         */
        set_list: function (e, self) {
            var level = e.currentTarget.dataset.level;
            var p_i = e.currentTarget.dataset.p_i;
            var c_i = e.currentTarget.dataset.c_i;
            var d_i = e.currentTarget.dataset.d_i;
            var list = this.data.list;
            if (level == 'p') {//省
                list[p_i] = self;
            } else if (level == 'c') {//市
                list[p_i][c_i] = self;
            } else if (level == 'd') {//区
                list[p_i][c_i][d_i] = self;
            }

            return list;
        },
        /**
         * 获取最后提交的内容
         * @param {要处理的数据信息} data
         * @param {选中的ID集合} id_arr
         * @param {选中的标题集合} text
         */
        get_form_data: function (data, id_arr = [], text = '') {
            var that = this;
            data.forEach(item => {
                if (item.checked_status == 1) {//当前信息的下级全部选中，则只取当前信息
                    id_arr.push(item.id);
                    if (text != '') text += ',';
                    text += item.title;
                } else {
                    if (item.child !== undefined && item.child.length > 0) {//当前信息有下级
                        var result = that.get_form_data(item.child, id_arr, text);
                        id_arr = result.id_arr;
                        text = result.text;
                    }
                }
            })
            return {id_arr: id_arr, text: text};
        },
        /**
         * 关闭弹窗
         */
        tree_close: function () {
            //关闭弹窗
            this.setData({_show: false});
            //调用回调函数
            this.triggerEvent('close', {});
        },



        /**
         * 提交
         */
        tree_submit: function () {
            console.log("submit",this.data)
            var list = this.data.list;
            var result = this.get_form_data(list);
            console.log("result", result)
            if (result.id_arr.length == 0) {
                showToastError("请选择地区")
                return false;
            }

            this.setData({
                _show: false,
                _text:result.text,
            });
            //调用回调函数
            this.triggerEvent('confirm', result);
        }

    },
})
